package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.OrganApplicationException;
import com.turing.post.organization.util.OrganRespCode;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.organization.util.Voucher;
import com.turing.post.organization.util.VoucherDao;
import com.turing.post.organization.util.VoucherInStockOrderDetail;
import com.turing.post.organization.util.VoucherInStockOrderDetailDao;
import com.turing.post.organization.util.VoucherStock;
import com.turing.post.organization.util.VoucherStockBusiness;
import com.turing.post.organization.util.VoucherStockDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * @author wzd
 * @2013-03-12
 */
@Stateless(mappedName = "organization.impl.VoucherStockBusinessImpl")
@Remote
@Local
public class VoucherStockBusinessImpl implements VoucherStockBusiness {

	@EJB(mappedName = "organization.impl.VoucherInStockOrderDetailDaoImpl")
	private VoucherInStockOrderDetailDao voucherInStockOrderDetailDaoImpl;// 凭证入库单明细

	@EJB(mappedName = "organization.impl.VoucherStockDaoImpl")
	private VoucherStockDao voucherStockDaoImpl;// 凭证库存

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;// 日志

//	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
//	private PCPSCommonDao pcpsCommonDaoImpl;// 主键
//
//	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
//	private IssueCompanyDao issueCompanyDaoImpl;// 发卡商
//
//	@EJB(mappedName = "organization.impl.VoucherStockDetailBusinessImpl")
//	private VoucherStockDetailBusiness voucherStockDetailBusinessDaoImpl;// 凭证出入库明细表

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;// 序号

	@EJB(mappedName = "organization.impl.VoucherDaoImpl")
	private VoucherDao voucherDaoImpl;// 凭证种类表

	/**
	 * 销售时查询凭证号是否可用
	 * 
	 * @param voucherStock
	 * @param input
	 * @return 返回空时未查询到
	 */
	@Override
	public VoucherStock getVoucherStockByCondition(VoucherStock voucherStock,
			PCPSWebInput input) throws PCPSApplicationException {
		if (input == null || PCPSUtil.isEmpty(input.getOperBranchNo())
				|| voucherStock.getVoucherId() == null
				|| PCPSUtil.isEmpty(voucherStock.getVoucherNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "必输参数项为空!");
		}

		VoucherStock vs = voucherStockDaoImpl.getVoucherStock(voucherStock);
		if (vs == null) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "凭证号不存在!");
		}
		if (PCPSUtil.isEmpty(vs.getSaleBranchNo())
				|| !input.getOperBranchNo().equals(vs.getSaleBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "该凭证不为当前销售机构凭证!");
		}

		if (!VoucherStock.Status_0.equals(vs.getStatus())) {
			String str = (vs.getStatus().equals("1")) ? "在途" : (vs.getStatus()
					.equals("9")) ? "丢失、损坏等" : "";
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "凭证状态为“" + str + "”状态!");
		}
		return vs;
	}

	public void insertVoucherStock(PCPSWebInput webInput,
			BigInteger voucherInStockOrderId) throws PCPSApplicationException {
		// 登录用户机构号为空
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		}
		// 操作员
		if (webInput.getOperId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"操作员为空!");
		}
		// 凭证入库单Id
		if (voucherInStockOrderId == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"凭证入库单Id为空!");
		}
		// 验证机构
		SysBranch branch = sysBranchDaoImpl.getSysBranchByBranchNo(webInput
				.getOperBranchNo());
		if (branch == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"机构号有误!");
		}
		String branchtype = branch.getBranchType();
		if (!branchtype.equals(SysBranch.SYSBRANCH_ISSUEBRANCH)) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"用户所在机构不是发卡机构!");
		}
		// 得到入库明细
		List<VoucherInStockOrderDetail> detail = voucherInStockOrderDetailDaoImpl
				.getVoucherInStockOrderDetailByVoucherInStockOrderIdNotPage(webInput,
						voucherInStockOrderId);
		if (detail != null && detail.size() > 0) {
			for (int i = 0; i < detail.size(); i++) {
				VoucherInStockOrderDetail indetail = detail.get(i);
				String StartVoucherNo = indetail.getStartVoucherNo();// 起始凭证号
				String EndVoucherNo = indetail.getEndVoucherNo();// 终止凭证号
				int Count = indetail.getCount();// 张数
				BigInteger VoucherId = indetail.getVoucherId();// 凭证种类ID
				// 验证库存是否存在
				BigInteger stockcount = voucherStockDaoImpl
						.getVoucherStockListByStatusTotal(webInput, indetail.getVoucherId(),
								StartVoucherNo, EndVoucherNo, null);
			
				if (stockcount.compareTo(BigInteger.ZERO)!=0) {
					throw new OrganApplicationException(
							OrganRespCode.RC_ARGS_NULL, "", "凭证号已经存在!");
				}
				Voucher voucher = voucherDaoImpl
						.getVoucherByVoucherId(VoucherId);
				if (voucher == null) {
					throw new OrganApplicationException(
							OrganRespCode.RC_ARGS_NULL, "", "凭证种类不存在!");
				}
				// int voucherNoLen = voucher.getVoucherNoLen().intValue();
				BigInteger voucherNo = BigInteger.ZERO;
				String vouNo = "";
				int vouchernolength=voucher.getVoucherNoLen().intValue();
				for (int ii = 0; ii < Count; ii++) {
					String cii = String.valueOf(ii);
					voucherNo = (new BigInteger(StartVoucherNo)
							.add(new BigInteger(cii)));
					vouNo=String.format("%0"+vouchernolength+"d",voucherNo);
					VoucherStock voucherStock = new VoucherStock();
					voucherStock.setVoucherNo(vouNo);
					voucherStock.setStatus(VoucherStock.Status_0);
					voucherStock.setIssueBranchNo(webInput.getOperBranchNo());
					voucherStock.setVoucherId(VoucherId);
					voucherStock.setIssueCompanyNo(webInput.getOperBranchNo()
							.substring(0, 6));
					// 插入库存
					voucherStockDaoImpl.insertVoucherStock(voucherStock);
					//					
				}
				// 出入库单ID
				/*BigInteger ioOrderId = pcpsCommonDaoImpl.getUniqueIntegerKey();
				if (ioOrderId == null) {
					throw new OrganApplicationException(
							OrganRespCode.RC_ARGS_NULL, "", "出入单ID为空!");
				}
				VoucherStockDetail voucherStockDetail = new VoucherStockDetail();// 出入库明细
				voucherStockDetail.setIoOrderId(ioOrderId);
				voucherStockDetail.setIssueCompanyNo(webInput.getOperBranchNo()
						.substring(0, 6));
				voucherStockDetail.setBranchNo(webInput.getOperBranchNo());
				voucherStockDetail.setTranTime(now);
				// 发卡商
				voucherStockDetail.setTranDate(ic.getTranDate());
				voucherStockDetail.setVoucherId(indetail.getVoucherId());
				voucherStockDetail.setStartVoucherNo(indetail
						.getStartVoucherNo());
				voucherStockDetail.setEndVoucherNo(indetail.getEndVoucherNo());
				voucherStockDetail.setCount(indetail.getCount());
				voucherStockDetail.setTranType(VoucherStockDetail.Status_0);
				voucherStockDetail.setOperId(webInput.getOperId());
				voucherStockDetailBusinessDaoImpl.insertVoucherStockDetail(
						webInput, voucherStockDetail);*/
			}
		} else {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"凭证入库有误!暂无入库明细!");
		}
	}

	/**
	 * 修改凭证库存表状态
	 * 
	 * @param VoucherStock
	 *            凭证库存
	 * @throws PCPSApplicationException
	 */
	public void updateVoucherStockByStatus(PCPSWebInput webInput,
			VoucherStock voucherStock) throws PCPSApplicationException {
		// 登录用户机构号为空
		if (PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION,
					OrganRespCode.ISSUE_INSERT_UPDATE, "登录用户机构号为NULL");
		}
		// 验证入库单ID
		if (voucherStock.getVoucherId() == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"凭证种类ID为空!");
		}
		// 凭证号
		if (PCPSUtil.isEmpty(voucherStock.getVoucherNo())) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"凭证号为空!");
		}
		VoucherStock voucherStock1 = voucherStockDaoImpl
				.getVoucherStock(voucherStock);
		if (voucherStock1 == null) {
			throw new OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
					"凭证库存不存在!");
		}
		/*
		 * String status = voucherStock.getStatus(); String status1 =
		 * voucherStock1.getStatus(); if (status1.equals(VoucherStock.Status_0))
		 * { if (!status.equals(VoucherStock.Status_1)) { throw new
		 * OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
		 * "凭证库存状态无效!不能做该操作!"); } } else if
		 * (status1.equals(VoucherStock.Status_1)) { if
		 * (!status.equals(VoucherStock.Status_0)) { throw new
		 * OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
		 * "凭证库存状态无效!不能做该操作!"); } } else if
		 * (status1.equals(VoucherStock.Status_0)) { if
		 * (!status.equals(VoucherStock.Status_9)) { throw new
		 * OrganApplicationException(OrganRespCode.RC_ARGS_NULL, "",
		 * "凭证库存状态无效!不能做该操作!"); } }
		 */
		// 修改
		voucherStockDaoImpl.updateVoucherStockByStatus(voucherStock);
		// 修改数据库操作日志
		insertRecordingOperationLog(webInput, "凭证库存修改", voucherStock,
				SysOperLog.operType_Edit, "VoucherNo:"
						+ voucherStock.getVoucherNo());
	}

	/**
	 * 入库撤销
	 * 
	 * @param VoucherStock
	 *            凭证库存
	 * @throws PCPSApplicationException
	 */
	public void deleteVoucherStock(PCPSWebInput webInput,
			VoucherInStockOrderDetail voucherInStockOrderDetail)
			throws PCPSApplicationException {
		if (voucherInStockOrderDetail != null) {
			String StartVoucherNo = voucherInStockOrderDetail
					.getStartVoucherNo();// 起始凭证号
			int Count = voucherInStockOrderDetail.getCount();// 张数
			BigInteger VoucherId = voucherInStockOrderDetail.getVoucherId();// 凭证种类ID
			Voucher voucher =voucherDaoImpl.getVoucherByVoucherId(VoucherId);
			if(voucher==null){
				throw new OrganApplicationException(
						OrganRespCode.RC_ARGS_NULL, "", "凭证种类不存在!");
			}
			int vouchernolength=voucher.getVoucherNoLen().intValue();			
			for (int ii = 0; ii < Count; ii++) {
				String cii = String.valueOf(ii);
				String VoucherNo = (new BigInteger(StartVoucherNo)
						.add(new BigInteger(cii))).toString();				
				VoucherNo=String.format("%0"+vouchernolength+"d", new BigInteger(VoucherNo));
				VoucherStock voucherStock = new VoucherStock();
				voucherStock.setStatus(VoucherStock.Status_0);
				voucherStock.setVoucherNo(VoucherNo);
				voucherStock.setVoucherId(VoucherId);
				voucherStock.setIssueCompanyNo(webInput.getOperBranchNo()
						.substring(0, 6));
				voucherStock.setIssueBranchNo(webInput.getOperBranchNo());
				// 得到入库单ID
				VoucherStock Isvoucherstock = voucherStockDaoImpl
						.getVoucherStock(voucherStock);
				if (Isvoucherstock == null) {
					throw new OrganApplicationException(
							OrganRespCode.RC_ARGS_NULL, "", "凭证号不存在!");
				}
				// 删除库存
				voucherStockDaoImpl.deleteVoucherStock(voucherStock);
				// 插入数据库操作日志
				insertRecordingOperationLog(webInput, "凭证入库撤销", voucherStock,
						SysOperLog.operType_Add, "VoucherNo："
								+ voucherStock.getVoucherNo());
			}
		}
	}

	private void insertRecordingOperationLog(PCPSWebInput webInput,
			String logName, VoucherStock obj, String operType,
			String lastFieldName) throws PCPSApplicationException {
		String logRemark = PCPSUtil.RecordingOperationLog(obj, lastFieldName);
		if (!PCPSUtil.isEmpty(logRemark)) {
			// 插入数据库日志
			SysOperLog sysOperLog = new SysOperLog();
			if (webInput != null && webInput.getOperId() != null) {
				sysOperLog.setOperId(webInput.getOperId());
				sysOperLog.setOperType(operType);
				sysOperLog.setLogName(logName);
				if (webInput != null) {
					sysOperLog.setIpAddress(webInput.getIpAddress());
				}
				if (!PCPSUtil.isEmpty(webInput.getOperBranchNo())) {
					sysOperLog.setIssueCompanyNo(webInput.getOperBranchNo()
							.substring(0, 6));
					sysOperLog.setBranchNo(webInput.getOperBranchNo());
				}
				sysOperLog.setRemark(logRemark);
				sysOperLogDaoImpl.insertSysOperLog(sysOperLog);
			}
		}
	}

	/**
	 * 凭证号前补0
	 * 
	 * @param str
	 * @param strLength
	 * @return
	 */
	public static String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		StringBuffer sb = null;
		while (strLen < strLength) {
			sb = new StringBuffer();
			sb.append("0").append(str);// 左(前)补0
			str = sb.toString();
			strLen = str.length();
		}
		// System.out.println(str);
		return str;
	}	
}
